<?php
/**
 * Description of Grid
 *
 * @author josema
 */
class Grid extends SystemObject{

    protected $properties = array();

    public function getJSON($objects) {
        
        $this->page = Input::get('page');
        $this->total = ceil(count($objects)/Input::get('rows'));
        $this->records = count($objects);

        $this->search ($objects);

        $this->usort($objects);

        $this->pagination ($objects);

        $arr = array();
        foreach ($objects as $obj){
            $arr [] = $obj->toArray();
        }

        $this->rows = $arr;

        return json_encode($this->toArray());
    }

    /**
     * Slice array of objects to current pagination.
     *
     * @author  jmlerma
     * @param   array $objects
     */
    private function pagination (&$objects) {
        $objects = array_slice($objects, (Input::get('page') -1) * Input::get('rows'), Input::get('rows'));
    }

    /**
     * Order objects.
     *
     * @author  jmlerma
     * @param   array Objects to sort
     */
    private function usort(&$objects){
        if (Input::get('sord') == 'asc')
            return usort($objects, array('Grid', 'usortAsc'));
        else
            return usort($objects, array('Grid', 'usortDesc'));
    }

    private function usortAsc($a, $b){
            return $a->{Input::get('sidx')} < $b->{Input::get('sidx')};
    }
    private function usortDesc($a, $b){
            return $a->{Input::get('sidx')} > $b->{Input::get('sidx')};
    }

    private function search(&$objects){
        if (Input::get('_search') == 'true')
            $objects = array_filter($objects, array('Grid', Input::get ('searchOper')));
	}

    private function eq($obj){
        return $obj->{Input::get('searchField')} == Input::get('searchString');
    }
    private function ne($obj){
        return $obj->{Input::get('searchField')} != Input::get('searchString');
    }
    private function lt($obj){
        return $obj->{Input::get('searchField')} < Input::get('searchString');
    }
    private function gt($obj){
        return $obj->{Input::get('searchField')} > Input::get ('searchString');
    }
    private function cn($obj){
        return strpos($obj->{Input::get ('searchField')}, Input::get ('searchString')) !== false;
    }

}
?>
